<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="global-drawer-tabs-separate" v-loading="isLoading">
      <el-tabs v-model="tabsData.active">
        <el-tab-pane
          v-for="item in tabsData.list"
          :key="item.name"
          :label="item.label"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>

      <div class="separate-main" v-if="detailData">
        <component
          ref="componentsRef"
          :is="getComponentName"
          :detailData="detailData"
        />
      </div>
    </div>

    <template #footer v-if="!detailData?.isAppealed">
      <el-button
        v-if="detailData?.state === '2'"
        type="primary"
        @click="handleClickSend"
        :loading="isLoading"
        >发货</el-button
      >
      <el-button
        v-if="detailData?.state === '3'"
        type="primary"
        @click="handleClickTake"
        :loading="isLoading"
        >立即签收</el-button
      >
      <el-button
        v-if="detailData?.state === '4'"
        type="primary"
        @click="handleClickComplete"
        :loading="isLoading"
        >结算</el-button
      >
      <!-- <PipeResetBtn :formEl="formRef">重置</PipeResetBtn> -->
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, PropType, watch, computed, markRaw, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

import DetailInfo from './detail-info.vue';
import DetailGoods from './detail-goods.vue';
import DetailLogistics from './detail-logistics.vue';
import { getOrderDetail, updateOrder } from '@/apis/order';

// 加载状态
const isLoading = ref(false);

// 表单 - ref
// const formRef = ref<InstanceType<typeof ElForm>>();
const componentsRef = ref<any>();

// tabs
const tabsData = reactive({
  active: '',
  list: [
    {
      label: '基本信息',
      name: 'info',
      component: markRaw(DetailInfo)
    },
    {
      label: '商品清单',
      name: 'goods',
      component: markRaw(DetailGoods)
    },
    {
      label: '物流信息',
      name: 'logistics',
      component: markRaw(DetailLogistics)
    }
  ]
});

// 初始化tabs
const initTabs = () => {
  const name = props.tabsActive || tabsData.list[0].name;
  tabsData.active = name;
};

// 详情
const detailData = ref<API.order.EntitySchema>();

const requestDataDetail = () => {
  isLoading.value = true;
  getOrderDetail(props.rowData.ownId!)
    .then((res) => {
      isLoading.value = false;
      detailData.value = res.data;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '50%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  // tab选中菜单
  tabsActive: {
    type: String,
    default: ''
  },

  rowData: {
    // type: Object as PropType<TempsPost>,
    type: Object as PropType<API.order.EntitySchema>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// computed - 动态组件
const getComponentName = computed(() => {
  const name = tabsData.active;
  const tabData = tabsData.list.find((item) => item.name === name);
  if (!tabData) return '';
  return tabData.component;
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;

    // 初始化tabs
    initTabs();

    // 从接口拿数据
    requestDataDetail();
  },
  {
    immediate: true
  }
);

// btn - 发货
const handleClickSend = async () => {
  // 判断是否在发货页面，否则跳转
  if (tabsData.active !== 'logistics') {
    tabsData.active = 'logistics';
    return;
  }

  // 二次确认
  try {
    await ElMessageBox.confirm(
      '请核实订单信息，不填写发货信息则代表订单无物流发货',
      '订单发货',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
  } catch (error) {
    return;
  }

  // 获取快递数据
  const logisticsList: API.logistics.EntityDto[] =
    componentsRef.value?.getFormData() || [];

  const dataOpt: API.order.EntityDto = {
    isLogistics: false
  };

  if (logisticsList.length) {
    dataOpt.isLogistics = true;
    dataOpt.logistics = logisticsList;
  }

  // 提交订单
  submitDataUpdate(dataOpt);
};

// btn - 立即签收
const handleClickTake = async () => {
  // 二次确认
  try {
    await ElMessageBox.confirm('请核实订单信息，是否立即签收？', '订单签收', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch (error) {
    return;
  }

  // 提交订单
  submitDataUpdate({});
};

// btn - 结算（立即完成）
const handleClickComplete = async () => {
  // 二次确认
  try {
    await ElMessageBox.confirm(
      '是否立即完成订单，完成后系统立即结算收益？',
      '订单结算',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
  } catch (error) {
    return;
  }

  // 提交订单
  submitDataUpdate({});
};

// submit - update
const submitDataUpdate = (dataOpt: API.order.EntityDto) => {
  isLoading.value = true;
  updateOrder(props.rowData.ownId!, dataOpt)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped></style>
